<?php

/**
 * Index controller class
 *
 */
class KadastrovaKartaController extends Client_Controller {

    private $_ERROR = '';

    public function init() {
        parent::init();
        $this->setActiveCat(978);
        $this->table_regions = new Client_Table_Regions($this->_lang);
        $this->_table = new Client_Table_App();
    }

    public function indexAction() {
        $cadnum = $this->_getParam('cadnum', '');
        $form = new Llib_Form($this->_request);

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('cadnum', $cadnum);
        $this->view->assign('reion-list', $this->table_regions->GetRegionsList());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    public function printAction() {
        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    /**
     * Graphic from pgsql
     *
     */
    public function findParcelAction() {
        $cadnum = $this->_getParam('cadnum', '');
//$cadnum = '0525685500:04:001:0004';

        $cadnum_arr = explode(':', $cadnum);
        if (count($cadnum_arr) != 4) {
            $ret['status'] = false;
            $ret['msg'] = 'Невірний формат кадастрового номеру';
            $this->ajaxOut($ret, 'json');
        }

        try {
            $sel = $this->_db2->select()
                    ->from('parcel900913')
                    ->where('koatuu = ?', floatval($cadnum_arr[0]))
                    ->where('zona = ?', floatval($cadnum_arr[1]))
                    ->where('kvartal = ?', floatval($cadnum_arr[2]))
                    ->where('parcel = ?', floatval($cadnum_arr[3]));

            $data = $this->_db2->select()
                    ->from($sel, array('st_xmin' => 'ST_XMin(ST_Union(the_geom_4284))',
                        'st_ymin' => 'ST_YMin(ST_Union(the_geom_4284))',
                        'st_xmax' => 'ST_XMax(ST_Union(the_geom_4284))',
                        'st_ymax' => 'ST_YMax(ST_Union(the_geom_4284))'
                    ))
                    ->query()
                    ->fetchAll(Zend_Db::FETCH_ASSOC);
        } catch (Exception $e) {
            echo $e->__toString();
            die();
        }

        $ret['status'] = true;
        $ret['data'] = $data;
        $this->ajaxOut($ret, 'json');
    }

    public function findRegionAction() {
        $koatuu = $this->_getParam('koatuu', '');
        $koatuu = str_pad($koatuu, 10, "0", STR_PAD_LEFT);

        try {
            $sel = $this->_db2->select()
                    ->from('obl_new')
                    ->where('koatuu = ?', $koatuu);

            $data = $this->_db2->select()
                    ->from($sel, array('st_xmin' => 'ST_XMin(ST_Union(the_geom_42_bl))',
                        'st_ymin' => 'ST_YMin(ST_Union(the_geom_42_bl))',
                        'st_xmax' => 'ST_XMax(ST_Union(the_geom_42_bl))',
                        'st_ymax' => 'ST_YMax(ST_Union(the_geom_42_bl))'
                    ))
                    ->query()
                    ->fetchAll(Zend_Db::FETCH_ASSOC);
        } catch (Exception $e) {
            echo $e->__toString();
            die();
        }

        $ret['status'] = true;
        $ret['data'] = $data;
        $this->ajaxOut($ret, 'json');
    }

    public function findDistrictAction() {
        $koatuu = $this->_getParam('koatuu', '');
        $koatuu = str_pad($koatuu, 10, "0", STR_PAD_LEFT);

        try {
            $sel = $this->_db2->select()
                    ->from('rayon_new')
                    ->where('koatuu = ?', $koatuu);

            $data = $this->_db2->select()
                    ->from($sel, array('st_xmin' => 'ST_XMin(ST_Union(the_geom_42_bl))',
                        'st_ymin' => 'ST_YMin(ST_Union(the_geom_42_bl))',
                        'st_xmax' => 'ST_XMax(ST_Union(the_geom_42_bl))',
                        'st_ymax' => 'ST_YMax(ST_Union(the_geom_42_bl))'
                    ))
                    ->query()
                    ->fetchAll(Zend_Db::FETCH_ASSOC);
        } catch (Exception $e) {
            echo $e->__toString();
            die();
        }

        $ret['status'] = true;
        $ret['data'] = $data;
        $this->ajaxOut($ret, 'json');
    }

    public function findCityAction() {
        $koatuu = $this->_getParam('koatuu', '');
        $koatuu = str_pad($koatuu, 10, "0", STR_PAD_LEFT);

        try {
            $sel = $this->_db2->select()
                    ->from('town')
                    ->where('koatuu = ?', $koatuu);

            $data = $this->_db2->select()
                    ->from($sel, array('st_xmin' => 'ST_XMin(ST_Union(the_geom_4284))',
                        'st_ymin' => 'ST_YMin(ST_Union(the_geom_4284))',
                        'st_xmax' => 'ST_XMax(ST_Union(the_geom_4284))',
                        'st_ymax' => 'ST_YMax(ST_Union(the_geom_4284))'
                    ))
                    ->query()
                    ->fetchAll(Zend_Db::FETCH_ASSOC);
        } catch (Exception $e) {
            echo $e->__toString();
            die();
        }

        $ret['status'] = true;
        $ret['data'] = $data;
        $this->ajaxOut($ret, 'json');
    }

    public function getRegionInfoAction() {
        $data = array();
        $koatuu = $this->_getParam('koatuu', '');
        $koatuu = str_pad($koatuu, 10, "0", STR_PAD_LEFT);

        $koatuu_region = str_pad(substr($koatuu, 0, 2), 10, "0", STR_PAD_RIGHT);
        $koatuu_district = str_pad(substr($koatuu, 0, 5), 10, "0", STR_PAD_RIGHT);

        try {
            $region = $this->_db2->select()
                    ->from('obl_new')
                    ->where('koatuu = ?', $koatuu_region)
                    ->query()
                    ->fetchAll(Zend_Db::FETCH_ASSOC);

            $district = $this->_db2->select()
                    ->from('rayon_new')
                    ->where('koatuu = ?', $koatuu_district)
                    ->query()
                    ->fetchAll(Zend_Db::FETCH_ASSOC);

            //print_r($koatuu_region); die();

            if (count($region) > 0)
                $data['region'] = $region[0]['natoobl'];
            if (count($district) > 0)
                $data['district'] = $district[0]['natoray'];
        } catch (Exception $e) {
            echo $e->__toString();
            die();
        }

        $ret['status'] = true;
        $ret['data'] = $data;
        $this->ajaxOut($ret, 'json');
    }

    public function getParcelInfoAction() {
        $data = array();
        $koatuu = $this->_getParam('koatuu', '');
        $zone = $this->_getParam('zone', '');
        $quartal = $this->_getParam('quartal', '');
        $parcel = $this->_getParam('parcel', '');

        $koatuu = str_pad($koatuu, 10, "0", STR_PAD_LEFT);

        try {
            $data = $this->_db2->select()
                    ->from('parcel900913')
                    ->where('koatuu = ?', floatval($koatuu))
                    ->where('zona = ?', floatval($zone))
                    ->where('kvartal = ?', floatval($quartal))
                    ->where('parcel = ?', floatval($parcel))
                    ->query()
                    ->fetchAll(Zend_Db::FETCH_ASSOC);
        } catch (Exception $e) {
            echo $e->__toString();
            die();
        }

        $ret['status'] = true;
        $ret['data'] = $data;
        $this->ajaxOut($ret, 'json');
    }

    public function getFeatureInfoAction() {
        $result = array(
            'title' => "Інформацію не знайдено",
            'body' => ""
        );
        $oInfo = array();

        preg_match_all("/<\s*table.*?>(.+?)<\s*\/\s*table\s*>/ui", str_replace("\n", "", $this->_getParam('html', '')), $tables);
        foreach ($tables[1] as $table_content) {
            preg_match_all("/<\s*tr.*?>(.+?)<\s*\/\s*tr\s*>/ui", $table_content, $rows);

            $th = null;
            $td = array();

            foreach ($rows[1] as $row_content) {
                if (preg_match_all("/<\s*th\s*>(.+?)<\s*\/\s*th\s*>/ui", $row_content, $t_headers))
                    $th = $t_headers[1];

                if (preg_match_all("/<\s*td\s*>(.+?)<\s*\/\s*td\s*>/ui", $row_content, $t_data))
                    $td[] = $t_data[1];
            }

            if (!empty($th) && !empty($td)) {
                $th_length = count($th);
                $td_length = count($td);

                for ($i = 0; $i < $td_length; $i++) {
                    $data = array();
                    for ($j = 0; $j < $th_length; $j++) {
                        $data[$th[$j]] = $td[$i][$j];
                    }
                    $oInfo[] = $data;
                }
            }
        }

        $infoType = null;
        $data = array();

        foreach ($oInfo as $info) {
            preg_match("/^(\w+)\..*$/ui", $info['fid'], $fid);

            if (empty($infoType)) {
                $infoType = $fid[1];
            }

            if ($infoType == $fid[1]) {
                $data[] = $info;
            }
        }

        switch ($infoType) {
            case 'dilanka':
                $result['title'] = "<h3>Ділянки(а)</h3>";
                $result['body'] = "<ul>";
                foreach ($data as $info) {
                    $koatuu = str_pad($info['koatuu'], 10, "0", STR_PAD_LEFT);
                    $zone = str_pad($info['zona'], 2, "0", STR_PAD_LEFT);
                    $quarter = str_pad($info['kvartal'], 3, "0", STR_PAD_LEFT);
                    $parcel = str_pad($info['parcel'], 4, "0", STR_PAD_LEFT);
                    $parcel_info = $this->_getParcelInfo($koatuu, $zone, $quarter, $parcel);

                    $result['body'] .= "<li><span><strong>";
                    $result['body'] .= $koatuu . ":";
                    $result['body'] .= $zone . ":";
                    $result['body'] .= $quarter . ":";
                    $result['body'] .= $parcel;
                    $result['body'] .= "</strong></span>";

                    if (!empty($parcel_info)) {
                        if (!empty($parcel_info[0]['ownershipvalue']))
                            $result['body'] .= "<div>" . trim($parcel_info[0]['ownershipvalue']) . "</div>";

                        if (!empty($parcel_info[0]['purpose']))
                            $result['body'] .= "<div>" . trim($parcel_info[0]['purpose']) . "</div>";

                        if (!empty($parcel_info[0]['area']))
                            $result['body'] .= "<div>" . trim($parcel_info[0]['area']) . " " . trim($parcel_info[0]['unit_area']) . "</div>";
                    }

                    $result['body'] .= "</li><br />";
                }
                $result['body'] .= "<ul>";
                break;
            case 'ikk':
                $info = $data[0];
                $koatuu = str_pad($info['koatuu'], 10, "0", STR_PAD_LEFT);
                $region_info = $this->_getRegionInfo($koatuu);

                if (!empty($region_info)) {
                    $result['title'] = "<h3>" . $region_info['region'] . " область</h3>";
                    $result['body'] = "<ul><li>";
                    $result['body'] .= '<div class="label">Район</div>';
                    $result['body'] .= '<div class="data">' . $region_info['district'] . '</div>';
                    $result['body'] .= "</li><li>";
                    $result['body'] .= '<div class="label">Коатуу</div>';
                    $result['body'] .= '<div class="data">' . $info['koatuu'] . '</div>';
                    $result['body'] .= "</li><li>";
                    $result['body'] .= '<div class="label">Зона</div>';
                    $result['body'] .= '<div class="data">' . $info['zona'] . '</div>';
                    $result['body'] .= "</li><li>";
                    $result['body'] .= '<div class="label">Квартал</div>';
                    $result['body'] .= '<div class="data">' . $info['kvart'] . '</div>';
                    $result['body'] .= "</li></ul>";
                }
                break;
            case 'rajonunion':
                $info = $data[0];
                $result['title'] = "<h3>" . $info['natoobl'] . " область</h3>";
                $result['body'] = "<ul><li>";
                $result['body'] .= '<div class="label">Район</div>';
                $result['body'] .= '<div class="data">' . $info['natoray'] . '</div>';
                $result['body'] .= "</li><li>";
                $result['body'] .= '<div class="label">Коатуу</div>';
                $result['body'] .= '<div class="data">' . $info['koatuu'] . '</div>';
                $result['body'] .= "</li></ul>";
                break;
            case 'obl':
                $info = $data[0];
                $result['title'] = "<h3>" . $info['natoobl'] . " область</h3>";
                $result['body'] = "<ul><li>";
                $result['body'] .= '<div class="label">Коатуу</div>';
                $result['body'] .= '<div class="data">' . $info['koatuu'] . '</div>';
                $result['body'] .= "</li></ul>";
                break;
        }

        $this->ajaxOut($result, 'json');
    }

    private function _getRegionInfo($koatuu) {
        $koatuu_region = str_pad(substr($koatuu, 0, 2), 10, "0", STR_PAD_RIGHT);
        $koatuu_district = str_pad(substr($koatuu, 0, 5), 10, "0", STR_PAD_RIGHT);

        try {
            $region = $this->_db2->select()
                    ->from('obl_new')
                    ->where('koatuu = ?', $koatuu_region)
                    ->query()
                    ->fetchAll(Zend_Db::FETCH_ASSOC);

            $district = $this->_db2->select()
                    ->from('rayon_new')
                    ->where('koatuu = ?', $koatuu_district)
                    ->query()
                    ->fetchAll(Zend_Db::FETCH_ASSOC);

            if (count($region) > 0)
                $data['region'] = $region[0]['natoobl'];

            if (count($district) > 0)
                $data['district'] = $district[0]['natoray'];
        } catch (Exception $e) {
            $data = null;
        }

        return $data;
    }

    private function _getParcelInfo($koatuu, $zone, $quarter, $parcel) {
        try {
            $data = $this->_db2->select()
                    ->from('parcel900913')
                    ->where('koatuu = ?', floatval($koatuu))
                    ->where('zona = ?', floatval($zone))
                    ->where('kvartal = ?', floatval($quarter))
                    ->where('parcel = ?', floatval($parcel))
                    ->query()
                    ->fetchAll(Zend_Db::FETCH_ASSOC);
        } catch (Exception $e) {
            $data = null;
        }

        return $data;
    }

    public function submitAppAction() {
        $data = $this->_request->getParams();
        $d = array();
        $ret['status'] = true;
        $ret['msg'] = 'Ваша заявка сформована!';

        $d['cadnum'] = iconv("UTF-8", "Windows-1251", $data['cadnum']);
        $d['no_parcel'] = filter_var($data['no_parcel'], FILTER_VALIDATE_BOOLEAN);
        $d['no_cadnum'] = filter_var($data['no_cadnum'], FILTER_VALIDATE_BOOLEAN);
        $d['error_location'] = filter_var($data['error_location'], FILTER_VALIDATE_BOOLEAN);
        $d['error_configuration'] = filter_var($data['error_configuration'], FILTER_VALIDATE_BOOLEAN);
        $d['error_use'] = filter_var($data['error_use'], FILTER_VALIDATE_BOOLEAN);
        $d['error_cross'] = filter_var($data['error_cross'], FILTER_VALIDATE_BOOLEAN);
        $d['no_errors'] = filter_var($data['no_errors'], FILTER_VALIDATE_BOOLEAN);
        $d['last_name'] = iconv("UTF-8", "Windows-1251", $data['last_name']);
        $d['first_name'] = iconv("UTF-8", "Windows-1251", $data['first_name']);
        $d['middle_name'] = iconv("UTF-8", "Windows-1251", $data['middle_name']);
        $d['pass_series'] = iconv("UTF-8", "Windows-1251", $data['pass_series']);
        $d['pass_number'] = iconv("UTF-8", "Windows-1251", $data['pass_number']);
        $d['identification_number'] = iconv("UTF-8", "Windows-1251", $data['identification_number']);
        $d['phone'] = iconv("UTF-8", "Windows-1251", $data['phone']);
        $d['email'] = iconv("UTF-8", "Windows-1251", $data['email']);
        $d['addr'] = iconv("UTF-8", "Windows-1251", $data['addr']);

        if (!($d['email'] = $this->check_email($data['email'])) && $ret['status']) {
            $ret['msg'] = $this->_ERROR;
            $ret['status'] = false;
        }

        if ($ret['status']) {
            $d['id'] = $this->_table->insert($d);
            if ($d['id']) {
                $ret['msg'] = 'Ваша заявка сформована!';
                $this->SendMail($d);
            } else {
                $ret['status'] = false;
                $ret['msg'] = 'Помилка формування заяви, зверніться до адміністратора.';
            }
        }

        $this->ajaxOut($ret, 'json');
    }

    //************************************************/
    //  Mailing
    //************************************************/

    public function SendMail($data) {
        $email = Zend_Registry::get('config')->contacts->email;
        $title = Zend_Registry::get('config')->title;
        $domain = Zend_Registry::get('config')->domains->front;

        $months = array('січня', 'лютого', 'березня', 'квітня', 'травня', 'червня', 'липня', 'серпня', 'вересня', 'жовтня', 'листопада', 'грудня');
        $today = getdate();

        $patterns[0] = "/{PHONE}/";
        $patterns[1] = "/{PASS_SERIES}/";
        $patterns[2] = "/{PASS_NUMBER}/";
        $patterns[3] = "/{CAD_NUM}/";
        $patterns[4] = "/{ADDRESS}/";
        $patterns[5] = "/{LAST_NAME}/";
        $patterns[6] = "/{FIRST_NAME}/";
        $patterns[7] = "/{MIDDLE_NAME}/";
        $patterns[8] = "/{IDENTIFICATION_NUMBER}/";
        $patterns[9] = "/{NO_PARCEL}.*?{NO_PARCEL}/";
        $patterns[10] = "/{NO_CADNUM}.*?{NO_CADNUM}/";
        $patterns[11] = "/{ERROR_LOCATION}.*?{ERROR_LOCATION}/";
        $patterns[12] = "/{ERROR_CONFIGURATION}.*?{ERROR_CONFIGURATION}/";
        $patterns[13] = "/{ERROR_USE}.*?{ERROR_USE}/";
        $patterns[14] = "/{ERROR_CROSS}.*?{ERROR_CROSS}/";
        $patterns[15] = "/{APP_DATE}/";
        $patterns[16] = "/{APP_NUMBER}/";

        $replacements[0] = $data['phone'];
        $replacements[1] = $data['pass_series'];
        $replacements[2] = $data['pass_number'];
        $replacements[3] = $data['cadnum'];
        $replacements[4] = $data['addr'];
        $replacements[5] = $data['last_name'];
        $replacements[6] = $data['first_name'];
        $replacements[7] = $data['middle_name'];
        $replacements[8] = $data['identification_number'];
        $replacements[9] = "";
        $replacements[10] = "";
        $replacements[11] = "";
        $replacements[12] = "";
        $replacements[13] = "";
        $replacements[14] = "";
        $replacements[15] = iconv("UTF-8", "Windows-1251", "\"" . $today['mday'] . "\" " . $months[$today['mon'] - 1] . " " . $today['year'] . " р.");
        $replacements[16] = str_pad($data['id'], 15, "0", STR_PAD_LEFT);

        if ($data['no_parcel']) {
            $patterns[9] = "/{NO_PARCEL}/";
        }

        if ($data['no_cadnum']) {
            $patterns[10] = "/{NO_CADNUM}/";
        }

        if ($data['error_location']) {
            $patterns[11] = "/{ERROR_LOCATION}/";
        }

        if ($data['error_configuration']) {
            $patterns[12] = "/{ERROR_CONFIGURATION}/";
        }

        if ($data['error_use']) {
            $patterns[13] = "/{ERROR_USE}/";
        }

        if ($data['error_cross']) {
            $patterns[14] = "/{ERROR_CROSS}/";
        }

        $tmpl = preg_replace($patterns, $replacements, file_get_contents("templates" . DIRECTORY_SEPARATOR . "dodatok8_1.html"));

        $mail = new Zend_Mail("Windows-1251");
        $mail->setBodyHtml($tmpl, 'Windows-1251');
        $mail->setFrom($email, $title);
        //$mail->addTo($data['email']);
        $mail->setSubject(iconv("UTF-8", "Windows-1251", '[' . $domain . '] - Зворотний з\'вязок!'));
        //$mail->send();
    }

    public function check_email($val) {
        $val = trim($val);
        if ($val == '') {
            $this->_ERROR = 'Необхідно ввести E-mail';
            return false;
        }

        $vald_email = new Zend_Validate_EmailAddress();
        if (!$vald_email->isValid($val)) {
            $this->_ERROR = implode(',', $vald_email->getMessages());
            return false;
        }

        return $val;
    }

}
